const {Service} = require('uni-cloud-router')
const {sendSms, loginBySms} = require("./utils/mobile");
const uniID = require('uni-id')
module.exports = class UserService extends Service {
    constructor(ctx) {
        super(ctx)
        this.usersCt = this.db.collection('uni-id-users')
        this.dbCmd = this.db.command
    }

    async loginOrRegister({username, mobile, yzmCode}) {
        console.log("loginOrRegister====", username)
        // 1.先判断手机号验证码是否正确
        const verifyRes = await uniID.verifyCode({mobile, code: yzmCode, type: 'register'})
        console.log("verifyCode======", verifyRes)
        if (verifyRes.code) return verifyRes //如果验证码错误
        else {// 2.验证成功
            // let user = await this.usersCt.where(this.dbCmd.or([{username}, {mobile}])).get()
            let userIn = await this.usersCt.where(this.dbCmd.or([{mobile}])).get()
            console.log("usersCt.get===========", userIn)
            // 3.判断用户是否存在
            if (userIn.data.length > 0) {//如果当前用户已经存在
                return this.userLogin({username: mobile, password: '123456'})
            } else {
                // 4.用户不存在就进行注册
                const userRegister = await uniID.register({
                    username, mobile, password: '123456', role: ['20210601092122'], status: 0, mobile_confirmed: 1
                })
                console.log("uniID.register========", userRegister)
                // 5.注册成功就登陆进去
                if(userRegister.code)return userRegister
                return this.userLogin({username: mobile, password: '123456'})
            }
        }
    }

    async sendMobileCode(mobile) {
        return sendSms(mobile, "register")
    }

    async login({username, password}) {
        const res = await uniID.login({username, password, needPermission: true})
        if (res.code) {
            return res
        }
        await this.checkToken(res.token)
        if (this.ctx.auth.role.includes('admin')) {
            return res
        }
        const navMenu = await this.service.menu.getMenu()
        if (navMenu.length) {
            return res
        }
        return {
            code: 10001,
            message: '该账号暂无权限登录'
        }
    }

    async userLogin({username, password}) {
        console.log("userLogin1=========", username, password)
        const res = await uniID.login({
            username, password, queryField: ['username', 'email', 'mobile']
        })
        console.log("userLogin2=========", res)
        if (res.code) {
            return res
        }
        await this.checkToken(res.token)
        return res
    }

    async logout(token) {
        return await uniID.logout(token)
    }

    async checkToken(token) {
        const auth = await uniID.checkToken(token)
        if (auth.code) {
            // 校验失败，抛出错误信息
            this.ctx.throw('TOKEN_INVALID', `${auth.message}，${auth.code}`)
        }
        this.ctx.auth = auth // 设置当前请求的 auth 对象
    }

    async hasAdmin() {
        const {total} = await this.db.collection('uni-id-users').where({
            role: 'admin'
        }).count()
        return !!total
    }
}
